package reflection;

import pojo.User;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

public class Test03 {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        final Class<User> userClass = User.class;

        //获得类的全类名，包名+类名
        System.out.println(userClass.getName());
        //获得类的类名
        System.out.println(userClass.getSimpleName());

        /**
         * 获得类的属性
         * getFields() 只能找到public的属性
         * getDeclaredFields() 能找到所有属性
         * 下面两个可以获得指定属性的值，不能逾越权限
         * getField(“。。”)
         * getDeclaredField(“。。”)
         */
        final Field[] fields = userClass.getFields();
        Arrays.stream(fields).forEach(System.out::println);
        System.out.println("--------------------");
        final Field[] declaredFields = userClass.getDeclaredFields();
        Arrays.stream(declaredFields).forEach(System.out::println);

        /**
         * 获得类的方法
         * getMethods() 获得本类和父类的所有public方法
         * getDeclaredMethods() 获得本类的所有方法
         */
        System.out.println("=================");
        final Method[] methods = userClass.getMethods();
        Arrays.stream(methods).forEach(System.out::println);
        System.out.println("-------------------");
        final Method[] declaredMethods = userClass.getDeclaredMethods();
        Arrays.stream(declaredMethods).forEach(System.out::println);

        /**
         * 获得指定方法
         * 没有参数的话，由于重载，则不能确定单个
         */
        final Method getName = userClass.getMethod("getName", null);
        final Method setName = userClass.getMethod("setName", String.class);
        System.out.println(getName);
        System.out.println(setName);

        /**
         * 获得类的构造器
         */
        System.out.println("==============");
        final Constructor<?>[] constructors = userClass.getConstructors();
        final Constructor<?>[] declaredConstructors = userClass.getDeclaredConstructors();
        final Constructor<User> constructor = userClass.getConstructor(null);
        Arrays.stream(constructors).forEach(System.out::println);
        Arrays.stream(declaredConstructors).forEach(System.out::println);
        System.out.println(constructor);

        final Constructor<User> declaredConstructor =
                userClass.getDeclaredConstructor(int.class, String.class, int.class);
        System.out.println("指定构造器：" + declaredConstructor);

        //使用构造器产生对象
        final User user = declaredConstructor.newInstance(1, "是我呀", 10);
        System.out.println(user);

    }
}
